#include "XXlaunch.h"
#include "../Utility/XXlayoutConstraint.h"
#include <QLabel>
#include <QTimer>
#include <QPixmap>

XXlaunch::XXlaunch()
    : QObject (){
    connect(this,&XXlaunch::sigLaunch,this,&XXlaunch::onThreadLaunch,Qt::QueuedConnection);
    connect(this,&XXlaunch::sigLaunch,this,&XXlaunch::onMainThreadLaunch);
    _delay = 0;
    _imagePath = "";
    _widget = nullptr;
    _activityView = nullptr;
    _launchBlock = nullptr;
    _threadLaunchBlock = nullptr;
    _mainThreadLaunchBlock = nullptr;
    moveToThread(&_thread);
    _thread.start();
}
XXlaunch::~XXlaunch(){
    _thread.quit();
    _thread.wait();
    if(_widget){
        delete  _widget;
        _widget = nullptr;
    }
}

void XXlaunch::configImage(const QString &imagePath){
    QPixmap pixmap(imagePath);
    pixmap = pixmap.scaledToWidth(1024,Qt::TransformationMode::SmoothTransformation);

    QLabel *image = new QLabel;
    image->setFixedSize(pixmap.size());
    image->setWindowFlags(Qt::Window|Qt::FramelessWindowHint);
    image->setAttribute(Qt::WA_StyledBackground);
    image->setPixmap(imagePath);

    _activityView = new XXactivityIndicatorView(image);
    _widget = image;
}
void XXlaunch::configDelay(int ms){
    _delay = ms;
}

void XXlaunch::configLaunchOnThread(std::function<void(void)> launch){
    _threadLaunchBlock = launch;
}
void XXlaunch::configLaunchOnMainThread(std::function<void(void)> launch){
    _mainThreadLaunchBlock = launch;
}

void XXlaunch::launch(){
    _widget->show();
    _activityView->show();
    if(_delay>0){
        QTimer::singleShot(_delay,this,&XXlaunch::sigLaunch);
    }
    else{
        emit sigLaunch();
    }
}

void XXlaunch::onThreadLaunch(){
    if(_threadLaunchBlock){
        _threadLaunchBlock();
    }
    emit sigFinished();
}
void XXlaunch::onMainThreadLaunch(){
    if(_mainThreadLaunchBlock){
        _mainThreadLaunchBlock();
    }
}
